﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TPL.Xna.Common
{
    /// <summary>
    /// Use collection of points for defining a sprite area.
    /// </summary>
    public class MeshSpriteArea : SpriteArea
    {
        private readonly IEnumerable<Vector2> _points;

        /// <summary>
        /// Create with top-left and bottom right corner.
        /// </summary>
        /// <param name="graphicsDevice"></param>
        /// <param name="points"></param>
        public MeshSpriteArea(GraphicsDevice graphicsDevice, IEnumerable<Vector2> points)
            : base(graphicsDevice)
        {
            _points = points;
        }

        /// <summary>
        /// Convinient method for getting horizon points
        /// </summary>
        /// <param name="horizonLine"></param>
        /// <param name="y"></param>
        /// <param name="pointCount"></param>
        /// <returns></returns>
        public static IEnumerable<Vector2> CreateHorizonPoints(Vector2 horizonLine, float y, int pointCount)
        {
            var res = new Vector2[pointCount];
            var segment = horizonLine.Length() / pointCount;
            for (int i = 0; i < pointCount; i++)
                res[i] = new Vector2(horizonLine.X + i * segment, y);
            return res;
        }

        /// <summary>
        /// Create a mesh of points to simulate the rectangle.
        /// </summary>
        /// <param name="graphicsDevice"></param>
        /// <returns></returns>
        protected override ShapeSprite CreateShape(GraphicsDevice graphicsDevice)
        {
            var shape = new ShapeSprite(graphicsDevice) { RenderType = RenderType.Point };
            shape.CreateMesh(_points.ToArray());
            return shape;
        }

        /// <summary>
        /// Support dectetion with <see cref="RectangleSpriteArea"/> only.
        /// Return true whenever there is a point inside the given rectangle.
        /// </summary>
        /// <param name="area"></param>
        /// <returns></returns>
        public override bool CollideWith(SpriteArea area)
        {
            if (!(area is RectangleSpriteArea)) throw new NotSupportedException();
            var rect = ((RectangleSpriteArea) area).GetCurrentAreaRectangle();
            return Shape.Any(p => rect.Contains((int) p.X, (int) p.Y));
        }

        /// <summary>
        /// Return true if any point is out of the given bound.
        /// </summary>
        /// <param name="bound"></param>
        /// <returns></returns>
        public override bool IsOutOfBound(Rectangle bound)
        {
            return Shape.Any(p => !bound.Contains((int)p.X, (int)p.Y));
        }
    }
}